'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { updateMenu } from '@/services/api';
import type { TMenuMenuType } from '@/types';
import type { IDifference, IMenu } from '@/interfaces';
import diff from 'microdiff';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import Box from '@/app/[locale]/admin/common/box';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateMenuInfo(
  this: any,
  {
    source,
    translatedFields,
  }: {
    source: IMenu;
    translatedFields: PrefixedTTranslatedFields<'menuAdminPage'>;
  },
) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    name: string;
    path: string;
    sort: number;
    menuType: TMenuMenuType;
  }>({
    name: source.name,
    path: source.path,
    sort: source.sort,
    menuType: source.menuType,
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const updateMenuMutation = useMutation(updateMenu);

  useEffect(() => {
    const diffData = diff(
      {
        name: source.name,
        path: source.path,
        sort: source.sort,
        menuType: source.menuType,
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const data = getDiffData(differenceData);
      const id = source.id;
      await updateMenuMutation.mutateAsync({
        id,
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.updateCompleted,
      });
    } catch (e) {
      updateMenuMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'sort') {
      setForm({ ...form, sort: parseInt(value) });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.properties.name}
          </label>
          <input
            type="text"
            className="form-control"
            name="name"
            value={form.name}
            onChange={onChangeForm}
            aria-describedby="name"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.path}
          </label>
          <input
            type="text"
            className="form-control"
            name="path"
            value={form.path}
            onChange={onChangeForm}
            aria-describedby="path"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.sort}
          </label>
          <input
            type="number"
            className="form-control"
            min={0}
            name="sort"
            value={form.sort}
            onChange={onChangeForm}
            aria-describedby="sort"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.menuType}
          </label>
          <select
            name="menuType"
            value={form.menuType}
            onChange={onChangeForm}
            className="form-select"
          >
            {['LINK', 'BUTTON'].map((item) => {
              return (
                <option key={item} value={item}>
                  {(translatedFields as any).enums.menuType[item]}
                </option>
              );
            })}
          </select>
        </div>

        <button
          type="submit"
          disabled={updateMenuMutation.isLoading || isDisabledSave}
          className="btn btn-success col col-lg-2 my-4"
        >
          {updateMenuMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
